package com.scaffold.springbootscaffold.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scaffold.springbootscaffold.entity.User;
import com.scaffold.springbootscaffold.mapper.UserMapper;
import com.scaffold.springbootscaffold.service.IUserService;
import com.scaffold.springbootscaffold.util.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private RedisUtil redisUtil;

    private static final String USER_CACHE_KEY_PREFIX = "user:username:";

    @Override
    public User getByUsername(String username) {
        // 先从Redis中获取
        String cacheKey = USER_CACHE_KEY_PREFIX + username;
        Object cacheUser = redisUtil.get(cacheKey);
        if (cacheUser != null) {
            return (User) cacheUser;
        }

        // Redis中没有，从数据库查询
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = getOne(wrapper);

        // 如果查询到数据，放入Redis缓存
        if (user != null) {
            redisUtil.set(cacheKey, user, 30, TimeUnit.MINUTES);
        }

        return user;
    }
} 